/**
* Script to assign annotations to stemmed text. Requires to 
* input files: one with stemmed ontology terms and one with 
* the text (one Medline Citation per line).
*/

// map to keep the ids with the stemmed concept name
def pato_id2stem = [:]
BufferedWriter bf = new BufferedWriter(new FileWriter(new File(args[2])))

// read the stemmed concept names
new File(args[0]).splitEachLine("\t") { splits ->
  if ( splits.size() > 1 ) {
    def ts = []
    ts.add(splits[1].trim())

    if ( splits.size() > 2 ) {
      def syns = splits[2].trim().split(";")
      // println syns
      if (syns.size() > 0 ) syns.each { syn -> 
        if (!syn.trim().equals("")) ts.add(syn.trim()) 
      }
    }
  
    pato_id2stem[splits[0].trim()] = ts
  }
}

// go through Medline Citations and assign MPs
new File(args[1]).splitEachLine("\t") { splits ->
  // textual data required ...
  if (splits.size() > 1) {
    def mp_id = splits[0].trim()
    def l = []

    pato_id2stem.each { p ->
      p.value.each { t ->
        // def common = .split(" ").grep(t)
        // if ( common.size() == t.size() ) {
        if ( splits[1].trim().contains(t) ) {
          l.add(p.key)
        }
      }
    }

    if ( l.size() > 0 ) {
      bf << mp_id 
      bf << "\t"
      bf << l.join("\t")
      bf << "\n"
    }

  }
}

bf.flush()
bf.close()
